package com.it.you.service.teacher.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.you.common.utils.ExecutorUtil;
import com.it.you.entity.dto.TeacherDTO;
import com.it.you.entity.pojo.TbTeacher;
import com.it.you.mapper.teacher.TeacherMapper;
import com.it.you.service.teacher.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Service
@Slf4j
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, TbTeacher> implements TeacherService {

    @Override
    public void saveOrUpdate(TeacherDTO teacherDTO) {
        TbTeacher tbTeacher = BeanUtil.copyProperties(teacherDTO, TbTeacher.class);
        if (ObjectUtils.isEmpty(tbTeacher.getId())) {
            this.save(tbTeacher);
        } else {
            //LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
            //queryWrapper.eq(Teacher::getId, teacher.getId());
            //this.update(null, queryWrapper); //此处的null会报sql错误
            //使用service的update(entity,条件构造器) entity的属性为null时，不会更新数据库字段
            //this.update(teacher, queryWrapper);

            tbTeacher.setIsDelete(true);
            updateById(tbTeacher);
        }
    }

    @Override
    public void saveTeachers(List<TeacherDTO> list) {
        List<TbTeacher> tbTeachers = BeanUtil.copyToList(list, TbTeacher.class);
        this.saveBatch(tbTeachers);
    }

    //使用多线程查询demo
    @Override
    public List<TbTeacher> getBatchTeacherByIdsAsync(List<Long> ids) throws InterruptedException{
        List<TbTeacher> result = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(ids.size());
        for(Long id : ids){
            ExecutorUtil.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        result.add(getById(id));
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        log.info("主线程等待子线程执行...");
        latch.await();
        log.info("子线程全部执行完毕");
        return result;
    }

    @Override
    public List<TbTeacher> getBatchTeacherByIdsSync(List<Long> ids) {
        return this.listByIds(ids);
    }

}
